package com.itrip.auth.service;

import com.itrip.beans.domain.ItripUser;
import com.itrip.dao.ItripUserMapper;
import com.itrip.utils.MD5;
import com.itrip.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class RegService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private MailService mailService;
    @Autowired
    private ItripUserMapper itripUserMapper;

    public boolean ckusr(String name){
        return itripUserMapper.selectByUserCode(name) != null ?false:true;
    }

    public int registerbyphone(ItripUser itripUser) throws Exception{
        itripUser.setUserPassword(MD5.md5(itripUser.getUserPassword()));
        if(itripUserMapper.selectByUserCode(itripUser.getUserCode()) != null){
            throw new Exception("该账户已存在!");
        }
        if(itripUserMapper.addItrip(itripUser)>0){
            smsService.sendMessage(itripUser.getUserCode(), RandomUtils.random(4));
            return 1;
        }else{
            throw new Exception("账户注册失败！");
        }
    }

    public boolean validatephone(String user,String code) throws Exception {
        String dbcode = smsService.getCode(user);
        if(dbcode == null){
            throw new Exception("激活号码不存在!");
        }
        if(!dbcode.equals(code)){
            throw new Exception("验证码输入错误!");
        }
        if(itripUserMapper.updateActivated(user)>0){
            return true;
        }
        return false;
    }

    public int doregister(ItripUser itripUser) throws Exception {
        itripUser.setUserPassword(MD5.md5(itripUser.getUserPassword()));
        if(itripUserMapper.selectByUserCode(itripUser.getUserCode()) != null){
            throw new Exception("该账户已存在!");
        }
        if(itripUserMapper.addItrip(itripUser)>0){
            String subject = "注册成功!请激活账户";
            String code = RandomUtils.random(4);
            String content = "注册成功,你的激活码是:"+code+"请于5分钟内输入";
            mailService.send(itripUser.getUserCode(),subject,content,code);
            return 1;
        }else{
            throw new Exception("账户注册失败！");
        }
    }

    public boolean activate(String user,String code) throws Exception {
        String dbcode = mailService.getCode(user);
        if(dbcode == null){
            throw new Exception("激活号码不存在!");
        }
        if(!dbcode.equals(code)){
            throw new Exception("验证码输入错误!");
        }
        if(itripUserMapper.updateActivated(user)>0){
            return true;
        }
        return false;
    }
}
